package org.example;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.net.MalformedURLException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController

public class FileDownloadController {

    private final Path fileStorageLocation = Paths.get("D:\\亚信\\共享\\金算盘").toAbsolutePath().normalize();

    @GetMapping("/view/{filename}")
    public ResponseEntity<Resource> viewFile(
            @PathVariable String filename,
            @RequestParam(value = "download", required = false, defaultValue = "false") boolean download) {
        try {
            Path filePath = fileStorageLocation.resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists() && resource.isReadable()) {
                String contentType = Files.probeContentType(filePath);
                if (contentType == null) {
                    contentType = "application/octet-stream";
                }

                MediaType mediaType = MediaType.parseMediaType(contentType);
                if (mediaType.getType().equals("text")) {
                    mediaType = new MediaType(mediaType.getType(), mediaType.getSubtype(), StandardCharsets.UTF_8);
                }

                HttpHeaders headers = new HttpHeaders();
                if (download) {
                    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + StringUtils.cleanPath(resource.getFilename()) + "\"");
                } else {
                    headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + StringUtils.cleanPath(resource.getFilename()) + "\"");
                }

                return ResponseEntity.ok()
                        .contentType(mediaType)
                        .headers(headers)
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (IOException ex) {
            return ResponseEntity.badRequest().build();
        }
    }
}

